package com.example.qinghe.frontController.businesstrip;

import com.alibaba.fastjson.JSON;
import com.example.qinghe.entity.Common;
import com.example.qinghe.entity.businesstrip.Form;
import com.example.qinghe.entity.businesstrip.Journey;
import com.example.qinghe.entity.businesstrip.Reimburse;
import com.example.qinghe.entity.communication.Staff;
import com.example.qinghe.service.businesstrip.CustomerService;
import com.example.qinghe.service.businesstrip.FormService;
import com.example.qinghe.service.businesstrip.JourneyService;
import com.example.qinghe.service.businesstrip.ReimburseService;
import com.example.qinghe.service.communication.StaffService;
import com.example.qinghe.service.communication.UserService;
import com.example.qinghe.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * AdminController
 * 
 * @author ruoyi
 * @date 2023-07-29
 */
@RestController
@RequestMapping("/front/journey")
@Validated
@CrossOrigin(origins = "*", maxAge = 3600,allowCredentials="true")
//swagger

@Api(tags = "差旅管理", description = "FrontReimburseController")
public class FrontReimburseController
{
    @Autowired
    private ReimburseService reimburseService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private JourneyService journeyService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private FormService formService;

    @Value("${upload-path}")
    private String path;
    @Value("${upload-qianzhui}")
    private String qianzhui;
    @Value("${upload-type}")
    private int type;



    @ApiOperation("报销添加，报销行程的花费")
    @PostMapping("/reimburse_add")
    public Result reimburse_add(Reimburse reimburse, HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long id=staff.getId();
       // Long id=1L;
      if(reimburse.getJid()<1&&reimburse.getMoney()<0){
          return Result.error("请检查数据是否正确");
      }
        int i = reimburseService.checkJourney(id, reimburse.getJid());
      if(i!=1)
          return Result.error("您不是该行程的创建人！");
      reimburse.setSid(id);
        Long add = reimburseService.add(reimburse);
        if(add>0)
            return Result.success("创建成功");
        return Result.error("创建失败");
    }

    @ApiOperation("报销删除，删除报销的行程，必须是未审批成功的")
    @PostMapping("/reimburse_del")
    public Result reimburse_del(@ApiParam(name = "id",value = "报销的id") @RequestParam(required = false) Long id,HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
       // Long sid=1L;
        Common common = reimburseService.selByid(id);
        if(common==null)
            return Result.error("没有这个报销记录");
        Long sid2=(Long)common.get("sid");
        int isover=(int)common.get("isover");
        if(sid2!=sid)
            return Result.error("您不是该报销记录的创建人");
        if(isover!=0)
            return Result.error("该记录已处理，无法删除");
        int del = reimburseService.del(id);
        if(del<1)
        return Result.error("删除失败");
        return Result.success("删除成功");
    }
    @ApiOperation("查看自己的报销记录")
    @PostMapping("/reimburse_sel")
    public Result reimburse_sel(
 @ApiParam(name = "type",value = "0是进行中，-1为未通过，1为已通过,其他为全部") @RequestParam(required = false) int type,
 @ApiParam(name = "start",value = "从第几条数据开始查") @RequestParam(required = false) Long start,
 @ApiParam(name = "limit",value = "要几条数据") @RequestParam(required = false) Long limit,HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        Common common = new Common();
        common.put("sid",sid);
        common.put("type",type);
        common.put("start",start);
        common.put("limit",limit);
        Long jid=0L;
        List<Common> sel = reimburseService.sel(common);

//        Common common2 = new Common();
//        common2.put("start",0);
//        common2.put("limit",2);
//        List<Common> sel = reimburseService.sel(common);
//        for (int i = 0; i < sel.size(); i++) {
//            jid=(Long)sel.get(i).get("jid");
//            common.put("id",jid);
//            List<Common> sel1 = journeyService.sel(common2);
//            sel.get(i).put("journey",sel1.get(0));
//        }
        return Result.success(sel);
    }


    @ApiOperation("查看详细的报销记录")
    @PostMapping("/reimburse_selById")
    public Result reimburse_selById(
            @ApiParam(name = "id",value = "报销id") @RequestParam(required = true) Long id,
  HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        Common common = new Common();
        common.put("id",id);
        Common sel = reimburseService.selByID(common);
        System.out.println(JSON.toJSONString(sel));
        if(sel!=null)
        {
            Long jid = (Long)sel.get("jid");
            common.put("id",jid);
            System.out.println(jid);
            Common common1 = journeyService.selById(common);

            String sidlist =(String) common1.get("sidlist");
            System.out.println(sidlist);
            common.put("sidlist",sidlist);
            List<Common> sellist = journeyService.sellist(common);
            common1.put("sidlistinfo",sellist);
            sel.put("journey",common1);

            String imglist =(String) sel.get("imglist");
            common.put("imglist",imglist);

        }

//        Common common2 = new Common();
//        common2.put("start",0);
//        common2.put("limit",2);
//        List<Common> sel = reimburseService.sel(common);
//        for (int i = 0; i < sel.size(); i++) {
//            jid=(Long)sel.get(i).get("jid");
//            common.put("id",jid);
//            List<Common> sel1 = journeyService.sel(common2);
//            sel.get(i).put("journey",sel1.get(0));
//        }
        return Result.success(sel);
    }
    @ApiOperation("行程添加")
    @PostMapping("/journey_add")
    public Result journey_add(Journey journey, HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        journey.setSid(sid);
        journey.setSidlist(","+journey.getSidlist()+",");
        Common common = new Common();
        common.put("sid",","+sid+",");
        common.put("starttime",journey.getStarttime());
        common.put("endtime",journey.getEndtime());
        int checktime = journeyService.checktime(common,journey.getSidlist());
        if(checktime>0)
        {
            Common sel = staffService.sel(Long.valueOf(checktime));
            return Result.error("员工"+sel.get("name")+"有时间冲突");
        }
        int add = journeyService.add(journey);
        if(add<1)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }

    @ApiOperation("行程删除")
    @PostMapping("/journey_del")
    public Result journey_del(@ApiParam(name = "id",value = "行程的id") @RequestParam(required = false) Long id, HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        Common common = new Common();
        common.put("id",id);
        common.put("start",0);
        common.put("limit",2);
        List<Common> sel = journeyService.sel(common);
        if(sel.size()<1)
            return Result.error("传入的行程id不正确");
        Long sid2=(Long)sel.get(0).get("sid");
        if(sid!=sid)
            return Result.error("这不是您的行程，无法删除");
        int isover=(int)sel.get(0).get("isover");
        if(isover==1)
        return Result.error("行程已审批完成，您无法删除");
        int del = journeyService.del(common);
        if(del<1)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }
   // @ApiParam(name = "type",value = "0是进行中，-1为未通过，1为已通过,3为未通过和已通过的集合") @RequestParam(required = false) int type,

    @ApiOperation("行程查找，查看自己的行程")
    @PostMapping("/journey_sel")
    public Result journey_sel(
            @ApiParam(name = "day",value = "查找的天数")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date day
   ,HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        System.out.println("sid:"+sid+",day:"+day);
        Common common = new Common();
        common.put("sid",","+sid+",");
        common.put("day",day);
        List<Common> sel = journeyService.sel(common);
        return Result.success(sel);
    }

    @ApiOperation("行程查找，根据id查看自己的行程")
    @PostMapping("/journey_selbyid")
    public Result journey_selbyid(
            @ApiParam(name = "id",value = "行程id")@RequestParam(required = true) Long id
            ,HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        Common common = new Common();
        common.put("id",id);
        Common sel = journeyService.selById(common);
        if(sel!=null)
        {
            System.out.println();
            String sidlist =(String) sel.get("sidlist");
            System.out.println(sidlist);
            common.put("sidlist",sidlist);
            List<Common> sellist = journeyService.sellist(common);
            sel.put("sidlistinfo",sellist);
            System.out.println(sellist);
        }
        return Result.success(sel);
    }

    @ApiOperation("行程查找，日历对应的红点,返回了一个list，1为有行程，0为无行程")
    @PostMapping("/journey_getdays")
    public Result journey_getdays(
            @ApiParam(name = "starttime",value = "查找的天数")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date starttime,
           @ApiParam(name = "endtime",value = "查找的天数")@DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(required = false) Date endtime
            ,HttpServletRequest request) {
//        Staff staff = userService.getStaff(request);
//        if(staff==null)
//            return Result.error("请先登录！");
//        Long sid=staff.getId();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar =Calendar.getInstance();
        Calendar calendar2 =Calendar.getInstance();
        calendar.setTime(starttime);
        calendar2.setTime(endtime);
        calendar2.add(Calendar.DAY_OF_YEAR,1);
        Long sid = 1L;
        Common common = new Common();
        common.put("sid", "," + sid + ",");
        common.put("starttime", starttime);
        common.put("endtime", endtime);
        List<Common> sel = journeyService.getDays(common);
        System.out.println(JSON.toJSONString(sel));
        String format;
        int count;
        ArrayList<Integer> list = new ArrayList<Integer>();
        Map map = new HashMap<>();
        if (sel.size() > 0) {
            for (int i = 0; i < sel.size(); i++) {
                map.put(sel.get(i).get("day"), sel.get(i).get("count"));
            }
        }
        System.out.println(calendar.before(calendar2));
        System.out.println(calendar.after(calendar2));
            while (calendar.before(calendar2)) {
                format = simpleDateFormat.format(calendar.getTime());

                Long value =(Long) map.get(format);
                count = (value == null ? 0 : value.intValue());

                if (count > 0)
                    list.add(1);
                else list.add(0);
                System.out.println(format + ":" + count);
                calendar.add(Calendar.DAY_OF_YEAR,1);

            }

            return Result.success(list);

    }



    @ApiOperation("账单添加")
    @PostMapping("/form_add")
    public Result form_add(Form journey, HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        journey.setSid(sid);
        int add = formService.add(journey);
        if(add<1)
            return Result.error("添加失败");
        return Result.success("添加成功");
    }

    @ApiOperation("账单删除")
    @PostMapping("/form_del")
    public Result form_del(@ApiParam(name = "id",value = "账单的id") @RequestParam(required = false) Long id, HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        Common common = new Common();
        common.put("id",id);
        common.put("start",0);
        common.put("limit",2);
        List<Common> sel = formService.sel(common);
        if(sel.size()<1)
            return Result.error("传入的账单id不正确");
        Long sid2=(Long)sel.get(0).get("sid");
        if(sid!=sid)
            return Result.error("这不是您的账单，无法删除");
        int isreimburse=(int)sel.get(0).get("isreimburse");
        if(isreimburse==1)
            return Result.error("账单已审批完成，您无法删除");
        int del = formService.del(common);
        if(del<1)
            return Result.error("删除失败");
        return Result.success("删除成功");
    }

    @ApiOperation("账单查找，查看自己的账单")
    @PostMapping("/form_sel")
    public Result form_sel(
            @ApiParam(name = "start",value = "从第几条数据开始查") @RequestParam(required = false) Long start,
            @ApiParam(name = "limit",value = "要几条数据") @RequestParam(required = false) Long limit,HttpServletRequest request)
    {
        Staff staff = userService.getStaff(request);
        if(staff==null)
            return Result.error("请先登录！");
        Long sid=staff.getId();
        // Long sid=1L;
        Common common = new Common();
        common.put("sid",sid);
        common.put("start",start);
        common.put("limit",limit);
        List<Common> sel = formService.sel(common);
        return Result.success(sel);
    }


//    @ApiOperation("文件上传,上传报销的图片，前端上传的名字是file：  " +
//            "var data = new FormData();\n" +
//            "\t\t\t      data.append(\"file\",img.files[0]);\n" +
//            "\t\t\t      $.ajax({\n" +
//            "\t\t\t        type : 'post',\n" +
//            "\t\t\t        url :'http://110.42.223.17:7322/front/main/upload',//地址改为后台给的上传地址\n" +
//            "\t\t\t        data :data,")
//    @PostMapping("/upload")
//    public Result upload2(@RequestParam(name="file") MultipartFile file){
//        Map<String,Object> m=new HashMap<>();
//        if (file!=null &&!file.isEmpty()) {
//            File f = new File(path);
//            if (!f.exists())
//                f.mkdirs();
//            //原来的文件名
//            String filename = file.getOriginalFilename();
//            String houzhui = filename.substring(filename.lastIndexOf('.'));
//            String newName = UUID.randomUUID() + houzhui;
//
//            try {
//                file.transferTo(new File(f, newName));
//                m.put("code",0);
//                return Result.success("img/"+newName,"添加成功");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        m.put("code",415);
//        m.put("msg","图片没有选择");
//        return Result.error(415,"图片没有选择");
//    }
    @ApiOperation("文件上传,上传报销的图片，前端上传的名字是files")
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("files") MultipartFile[] files) {
        try {
            for (MultipartFile file : files) {
                System.out.println("nvsbnrs");
                saveFile(file);
            }
            return "文件上传成功！";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }

    private void saveFile(MultipartFile file) throws IOException {
        System.out.println("vnfisbngui");
        File f = new File(path);
        if (!f.exists())
            f.mkdirs();

        //原来的文件名
        String filename = file.getOriginalFilename();
        String houzhui = filename.substring(filename.lastIndexOf('.'));
        String newName = UUID.randomUUID() + houzhui;

        // 指定文件保存的路径和文件名
        String filePath = "C:/temp/"; // 请根据实际情况修改路径
        String fileName = file.getOriginalFilename();
        File dest = new File(f, newName);
        System.out.println(f+"/"+newName);
        // 将文件保存到指定路径
        file.transferTo(dest);

    }






}
